package br.com.equipe1.model.service;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import br.com.equipe1.model.EnderecoEmpresa;
import br.com.equipe1.utils.FacesUtils;

public class EnderecoEmpresaService {
	
	private final static String PERSISTENCE_UNIT_NAME = "Projeto";
	private EntityManager entityManager;
	private EntityManagerFactory factory;
	
	public EnderecoEmpresaService () {
		factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
	}

	public EntityManager getEntityManager() {
		return factory.createEntityManager();
	}
	
	public void salvar(EnderecoEmpresa enderecoEmpresa){
		try {
			entityManager = getEntityManager();
			entityManager.getTransaction().begin();
			if(enderecoEmpresa.getIdEndereco() == null){
				entityManager.persist(enderecoEmpresa);				
			} else {
				entityManager.merge(enderecoEmpresa);
			}
			entityManager.getTransaction().commit();
		} catch (Exception e) {
			FacesUtils.error("Erro ao salvar empresa. Contate administrador");
			System.out.println(e.getMessage());
			entityManager.getTransaction().rollback();
		} finally {
			entityManager.close();
		}
	}	

}
